package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

const AdminPrefix = "admin_"
const BlogPrefix = "b_"

func Init() {
	//注册model
	RegisterModels()
	defaultDb()
	blog()
}

func RegisterModels() {
	_ = orm.RegisterDriver("mysql", orm.DRMySQL)
	adminModels := []interface{}{
		NewAdmin(),
		NewRole(),
		NewMenu(),
		NewRoleMenu(),
	}
	blogModels := []interface{}{
		NewBlog(),
		NewCategory(),
	}
	orm.RegisterModelWithPrefix(AdminPrefix, adminModels...)
	orm.RegisterModelWithPrefix(BlogPrefix, blogModels...)
}

//默认数据库
func defaultDb() {
	dbhost := beego.AppConfig.String("dbhost")
	dbport := beego.AppConfig.String("dbport")
	dbuser := beego.AppConfig.String("dbuser")
	dbpassword := beego.AppConfig.String("dbpassword")
	dbname := beego.AppConfig.String("dbname")
	if dbport == "" {
		dbport = "3306"
	}
	dsn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8&loc=Asia%2FShanghai"
	err := orm.RegisterDataBase("default", "mysql", dsn)
	checkError(err)
}

func reptile() {
	host := beego.AppConfig.String("dbhost")
	port := beego.AppConfig.String("dbport")
	user := beego.AppConfig.String("dbuser")
	password := beego.AppConfig.String("dbpassword")
	dbname := beego.AppConfig.String("dbname")
	if port == "" {
		port = "3306"
	}
	goBlog := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8&loc=Asia%2FShanghai"
	err := orm.RegisterDataBase("blog", "mysql", goBlog)
	checkError(err)
}

func blog() {
	host := beego.AppConfig.String("dbhost")
	port := beego.AppConfig.String("dbport")
	user := beego.AppConfig.String("dbuser")
	dbName := beego.AppConfig.String("dbname")
	password := beego.AppConfig.String("dbpassword")
	if port == "" {
		port = "3306"
	}
	goBlog := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + dbName + "?charset=utf8&loc=Asia%2FShanghai"
	err := orm.RegisterDataBase("blog", "mysql", goBlog)
	checkError(err)
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

//返回带前缀的表名
func TableName(str string, prefix ...string) string {
	var pre string
	if len(prefix) == 0 {
		pre = beego.AppConfig.String("dbprefix")
	} else {
		pre = prefix[0]
	}
	return pre + str
}
